package cn.tedu._05weibo.base.exception;

import cn.tedu._05weibo.base.response.JsonResult;
import cn.tedu._05weibo.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        /*
            1. 封装类参数校验: 获取校验失败的提示消息;
               ex.getFieldError().getDefaultMessage();
         */
        String data = ex.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException:" + data);

        //{"state": 5000, "message":"请求参数错误", "data":"提示消息"}
        return new JsonResult(StatusCode.VALIDATED_ERROR, data);
    }

    /**
     *   validation处理非封装参数[声明参数]校验的异常处理方法;
     */
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        String data = ex.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException:" + data);

        return new JsonResult(StatusCode.VALIDATED_ERROR, data);
    }
}
